/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package framework;

import java.util.Iterator;

/**
 *
 * @author Josh
 */
public class LinkedList<T> implements Iterable<T>,Iterator<T> {
    
    private Node root, last;
    private transient Node iterTemp;
    private boolean isIterating;
    
    public LinkedList() {
        root = null;
        iterTemp = null;
        isIterating = false;
    }
    
    public void add(T dat) {
        if(root == null)  {
            root = new Node(dat);
            last = root;
        }
                
        else {
            Node n = new Node(dat);
            n.next = root;
            root.prev = n;
            root = n;
            
        }
    }
    
    public void remove(int index) {
        int count = 0;
        Node temp = root;
        
        while(count < index && temp != null) {
            temp = temp.next;
            count++;
        }
        
        if(temp == null) 
            throw new RuntimeException("Out of Bounds");
        
        if(temp == root) {
            root = root.next;
        }
        else if (temp == last) {
            last = last.prev;
        }
        else {
            temp.prev = temp.next;
        }
        
        
    }

    @Override
    public Iterator<T> iterator() {
        return this;
    }
    
    

    @Override
    public boolean hasNext() {
        if(!isIterating) {
            iterTemp = root;
            isIterating = true;
        }
        
        
            
        if(iterTemp == null) {
            isIterating = false;
            return false;
        }
        
        return true;
        
    }

    @Override
    public T next() {
        Node hold = iterTemp;
        iterTemp = iterTemp.next;
        
        return hold.data;
        
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    public T[] toArray(T[] arr) {
        int pos = 0;
        for(T a : this) {
            arr[pos] =  a;
            pos++;
        }
        
        return arr;
    }
    
    public class Node {
        Node next,prev;
        T data;
        
        public Node(T dat) {
            data = dat;
            next = null;
            prev = null;
        }
    }
    
    
    
    
    
    
    
}
